<?php
/**
 * @package html
 */
require_once '_dbobject.php';
require_once '_localemanager.php';
require_once '_img.php';
require_once '_system.php';
require_once '_stringex.php';
require_once '_htmlbase.php';

/**
 * Class which encapsulates view of offers in the admin list view.
 */
class HtmlUserAdmin extends HtmlBase {
	/**
	 * @see HtmlBase::fetchInstance
	 * @return HtmlUserAdmin
	 */
	static function fetchInstance(resource $resource) {
		try {
			return new HtmlUserAdmin($resource);
		} catch(ExceptionResourceEmpty $e) {
			return false;
		}
	}
	
	/**
	 * @see HtmlBase::fetchDbObject
	 */
	protected function fetchDbObject(resource $resource) {
		$this->dbObject = mysql_fetch_object($resource, 'User');
		return $this->dbObject;
	}
	
	/**
	 * Gather all necessary data for creating working pagination.
	 * 
	 * @see HtmlBase::fetchDataForPagesCounting
	 * 
	 * Following class static members are filled:
	 * @see HtmlBase::$countOfPages
	 * @see HtmlBase::$currentPage
	 * @see HtmlBase::$hrefPages
	 * @see HtmlBase::$queryLimit
	 * 
	 * @param int $countInView - desired count of entities on one page
	 * @param string $querySpec - specification of select query
	 * @param string $tableName - name of the table to select from
	 */
	public static function fetchDataForPagesCounting(int $countInView, $querySpec, $tableName = null) {
		return parent::fetchDataForPagesCounting($countInView, $querySpec, 'users');
	}
	
	/**
	 * Url link to an user with id $id.
	 * 
	 * @param string|int #$id - id of user
	 * @return string - url
	 */
	public static function hrefToUser($id) {
		return "?".Constants::REQ_ACTION."=".Constants::REQ_ACTION_REGISTATION
				."&amp;".Constants::REQ_TYPE."=".$id;
	}
	
	/**
	 * Generate html code, but don't outpu it yet.
	 * @throws Exception - in case of error
	 * @see HtmlObject::processMe
	 */
	function processMe() {
		$cm = CodeManager::getCodeManager();
		$info = SiteContext::getSiteContext();
		$dbObject = $this->dbObject;
		$href = self::hrefToUser($dbObject->id);
		$this->buffer = "
			<tr class=\"_TEMPLATE_ODDOREVEN_\">
				<td class=\"first\">
					<input type=\"checkbox\" value=\"user-$dbObject->id\" />
				</td>
				<td>
					$dbObject->login
				</td>
				<td>
					" . Definitions::getSetupGroupsSafe($dbObject->group) . "
				</td>
				<td>
					$dbObject->firstName			
				</td>
				<td>
					$dbObject->surName
				</td>
				<td>
					$dbObject->mail			
				</td>
				<td class=\"last\">
					<a href=\"$href\" title=\"". $cm->get("30063") . "$dbObject->id\">".$cm->get("30027")."</a>
				</td>
			</tr>";
	}
	
	/**
	 * Map which connects a parameter from an url with
	 * an attribute of HtmlBase::$dbObject
	 */
	private static $sortValMap = array (
		Constants::REQ_SORTVAL_LOGIN => "login",
		Constants::REQ_SORTVAL_GROUP => "group",
		Constants::REQ_SORTVAL_FIRSTNAME => "firstName",
		Constants::REQ_SORTVAL_SURNAME => "surName",
		Constants::REQ_SORTVAL_MAIL => "mail"
	);
	
	/**
	 * Provides extra scalability then just HtmlObject::init
	 *
	 * @see HtmlObject::init
	 * 
	 * @param string $query
	 * @param bool $displayErrors
	 * @param bool $availableSort
	 * @param bool $availableItemsCountSetting
	 */
	public static function initWithFullQuery($query, $displayErrors = false, $availableSort = true, $availableItemsCountSetting = true) {
		$logger = Logger::getLogger();
		$info = SiteContext::getSiteContext();
		$cm = CodeManager::getCodeManager();
		
		if (!Policy::isAdminView())  {// TODO check for accessibility
			Error::getError()->addErrorMessage($cm->get("10005"));
			return;
		}
		
		// Get connector
		$res = $info->getDBConnector()->query($query);
		
		
		echo "
			<table id=\"offer-list\">
				<thead>
					<tr>
						<td class=\"first\">
							<input type=\"checkbox\" id=\"offer-list-selectall\" />
						</td>";
		$cm = CodeManager::getCodeManager();
		$columnsSpecs = array(
		
			array(Constants::REQ_SORTVAL_LOGIN, $cm->get("30001")),
			array(Constants::REQ_SORTVAL_GROUP, $cm->get("30065")),
			array(Constants::REQ_SORTVAL_FIRSTNAME, $cm->get("30007")),
			array(Constants::REQ_SORTVAL_SURNAME, $cm->get("30008")),
			array(Constants::REQ_SORTVAL_MAIL, $cm->get("30006"))
		);
		foreach($columnsSpecs as $params) {
			if ($availableSort) {
				echo self::headerColumn($params[0], $params[1]);
			} else {
				echo "<td>$params[1]</td>";
			}
		}
		echo '
						<td class="last">
						</td>
					</tr>
				</thead>
				<tfoot>
					<tr>';
		if (Policy::isAdminView()) {
			echo '
						<td class="first" colspan="3">';
			echo '
							<a class="light" href="javascript: Ajax.getIdsForSelectedUsersAndDelete(this); ">'.$cm->get("30058").' <img src="/img/o_drop.png" alt="remove" /></a>
							<!--&nbsp;|&nbsp;
							<a class="light" href="javascript: Ajax.getIdsForSelectedOffersAndHide(this); ">Hide selected</a>-->
						';
							
		} else {
			echo '
						<td class="first" colspan="3">';
			if (@$_GET[Constants::REQ_ACTION] == Constants::REQ_ACTION_INTERESTEDIN) {
				echo '
							<a class="light" href="javascript: Ajax.getIdsForSelectedOffersAndRemoveInListView(this); ">'.$cm->get("30058").'</a>
							'.$cm->get("30059").'.';
			} else {
				echo '
							<a class="light" href="javascript: Ajax.getIdsForSelectedOffersAndAddInListView(this); ">'.$cm->get("30055").'</a>
							'.$cm->get("30056").'
							<a class="light" href="?'.Constants::REQ_ACTION.'='.Constants::REQ_ACTION_INTERESTEDIN.'" >
								'.$cm->get("30057").'
							</a>.';
			}
		}
		echo '
						</td>
						<td class="last" colspan="4">';
		if ($availableItemsCountSetting) {
			echo '
							'.$cm->get("10020").': 
							<select onchange="Ajax.setCountOfPagesForListView(this.value);" class="small" name="offer-list-defaultpagescount">';
			foreach (Constants::$SETUP_COUNTOFITEMSINLISTVIEW as $availableCountOfItems) {
				if ($availableCountOfItems == $info->getCountOfItemsInListView()) {
					echo "
								<option value=\"$availableCountOfItems\" selected=\"selected\">$availableCountOfItems</option>";
				} else {
					echo "
								<option value=\"$availableCountOfItems\">$availableCountOfItems</option>";
				}
			}
		echo '				
							</select>';
		}
		echo '
						</td>
					</tr>
				</tfoot>
				<tbody>';
		for($i = 0; $htmlOfferAdmin = HtmlUserAdmin::fetchInstance($res); ++$i) {
			Logger::getLogger()->debug("processing offer: " . $htmlOfferAdmin->dbObject->id);
			try {
				$htmlOfferAdmin->processMe();
				$htmlOfferAdmin->replaceTemplate("/_TEMPLATE_ODDOREVEN_/", $i % 2 == 0 ? "even" : "odd");
				$htmlOfferAdmin->flushMe();
			} catch (Exception $e) {
				$logger->error("Cannot display offer: '".$htmlOfferAdmin->dbObject->id."' due to error: '$e'");
				if ($displayErrors) {
					Error::getError()->addErrorMessage("Cannot display offer '".$htmlOfferAdmin->iddbObject->id."', please contact administrator.");
				}
			}
		}
		echo '
				</tbody>
			</table>';
	}
	
	/** database table name */
	private static $dbTableMame = "users";
	
	/**
	 * Method which should group together number of calls of HtmlObject::processMe and HtmlObject::flushMe
	 * in a cycle.
	 * @see HtmlObject::init
	 *
	 * @param bool $querySpec
	 * @param bool $displayErrors
	 */
	public static function init($querySpec = null, $displayErrors = false) {
		$logger = Logger::getLogger();
		$info = SiteContext::getSiteContext();
		$cm = CodeManager::getCodeManager();
		
		if (!Policy::isAdminView())  {// TODO check for accessibility
			Error::getError()->addErrorMessage($cm->get("10005"));
			return;
		}
			
		if ($querySpec == null) {
			$querySpec = "";
		}
		
		// Fetch datas for pages counting
		self::fetchDataForPagesCounting($info->getCountOfItemsInListView(), $querySpec);
		
		// Sort output
		$query = "";
		if (@isset($_REQUEST[Constants::REQ_SORTVAL]) && @isset($_REQUEST[Constants::REQ_SORTTYPE])
			&& @self::$sortValMap[$_REQUEST[Constants::REQ_SORTVAL]] && @self::$sortTypeMap[$_REQUEST[Constants::REQ_SORTTYPE]]) {
			$query = " ORDER BY `".self::$dbTableMame."`.`".self::$sortValMap[$_REQUEST[Constants::REQ_SORTVAL]]."` ".self::$sortTypeMap[$_REQUEST[Constants::REQ_SORTTYPE]];
		}
			
		// Decide if click on column header will sort ascending or descending
		if (@$_REQUEST[Constants::REQ_SORTTYPE] == Constants::REQ_SORTTYPE_ASC)
			$sortType = Constants::REQ_SORTTYPE_DESC;
		else
			$sortType = Constants::REQ_SORTTYPE_ASC;
		
		$hrefDefault = $info->getSiteInf()->urlRelativeWithoutSomeVariables(array(
				Constants::REQ_SORTTYPE => true, 
				Constants::REQ_SORTVAL => true, 
				Constants::REQ_TYPEOFVIEW => true
		));
		
		self::$href = Common::addParamsToUrl($hrefDefault, Constants::REQ_SORTTYPE, $sortType,
				Constants::REQ_SORTVAL, "_TEMPLATESORT_",
				Constants::REQ_TYPEOFVIEW, Constants::REQ_TYPEOFVIEW_LIST
		);
		
		self::$hrefAsc = Common::addParamsToUrl($hrefDefault, Constants::REQ_SORTTYPE, Constants::REQ_SORTTYPE_ASC, 
				Constants::REQ_SORTVAL, "_TEMPLATESORT_", 
				Constants::REQ_TYPEOFVIEW, Constants::REQ_TYPEOFVIEW_LIST);
		self::$hrefDesc = Common::addParamsToUrl($hrefDefault, Constants::REQ_SORTTYPE, Constants::REQ_SORTTYPE_DESC, 
				Constants::REQ_SORTVAL, "_TEMPLATESORT_", 
				Constants::REQ_TYPEOFVIEW, Constants::REQ_TYPEOFVIEW_LIST);
		
		if (!Policy::isAdminView()) {
			echo '
			<div class="text left">
				<a href="'.
					Common::addParamToUrl(
							$info->getSiteInf()->urlRelativeWithoutSomeVariables(array(Constants::REQ_TYPEOFVIEW => true)),
							Constants::REQ_TYPEOFVIEW, Constants::REQ_TYPEOFVIEW_THUMB)
					."\">show thumbnails</a>
			</div>";
		}
		echo "
			<div class=\"offer-list-pages\">";

		// display page numbers
		for ($page = 1; $page <= self::$countOfPages; ++$page) {
			if ($page == self::$currentPage) {
				echo '
				<span>&nbsp;'.
				$page.'&nbsp;</span>';
			} else {
				echo "
				<a href=\"".Common::addParamsToUrl(self::$hrefPages, Constants::REQ_PAGE, $page)."\">$page</a>";
			}
		}
		echo "
			</div>";
		if (!Policy::isAdminView()) {
			echo "<div class=\"cleaner\"></div>";
		}
		self::initWithFullQuery(Constants::DB_QUERY_USERS_ALL.$querySpec.$query.self::$queryLimit, $displayErrors, true, true);
	}
}
?>